package org.freespace.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.freespace.Constant;
import org.freespace.model.*;
import org.freespace.mapper.JmxParamfileMapper;
import org.freespace.service.IJmxParameterService;
import org.freespace.service.IJmxParamfileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.freespace.service.IJmxUserDefineVariableService;
import org.freespace.utils.SessionUtil;
import org.freespace.utils.response.CommonResult;
import org.freespace.vo.JmxParamfileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * jmx参数化文件表 服务实现类
 * </p>
 *
 * @author liuqi
 * @since 2023-05-12
 */
@Service
public class JmxParamfileServiceImpl extends ServiceImpl<JmxParamfileMapper, JmxParamfile> implements IJmxParamfileService {

    @Autowired
    IJmxParameterService parameterSerivice;
    @Autowired
    IJmxParamfileService paramfileService;

    @Autowired
    IJmxUserDefineVariableService userDefineVariableService;

    @Override
    public void addParamFile(MultipartFile[] file, Integer scriptId) throws IOException {
        String userName = SessionUtil.getCurrentUser();

        //获取脚本解析后参数化文件的记录
        Map<String, String> jmxParamFileMap = new HashMap<>();
        List<JmxParameter> jmxParameters = parameterSerivice.list(Wrappers.<JmxParameter>lambdaQuery().eq(JmxParameter::getJmxId, scriptId));
        if (!jmxParameters.isEmpty()) {
            for (JmxParameter jmxParameter : jmxParameters) {
                if (StringUtils.isNotBlank(jmxParameter.getFileName()) && StringUtils.isNotBlank(jmxParameter.getVariableNames())) {
                    jmxParamFileMap.put(jmxParameter.getFileName(), jmxParameter.getVariableNames());
                }
            }
        }

        //获取是否使用了用户自定义变量
        Map<String, String> newMap = new HashMap<>();
        List<JmxUserDefineVariable> jmxUserDefineVariables = userDefineVariableService.list(Wrappers.<JmxUserDefineVariable>lambdaQuery().eq(JmxUserDefineVariable::getJmxId, scriptId));
        if (!jmxUserDefineVariables.isEmpty()) {
            if (jmxParamFileMap.size() > 0) {
                for (Map.Entry<String, String> entiry : jmxParamFileMap.entrySet()) {
                    String oldName = entiry.getKey();
                    for (int i = 0; i < jmxUserDefineVariables.size(); i++) {
                        JmxUserDefineVariable jmxUserDefineVariable = jmxUserDefineVariables.get(i);
                        if (oldName.contains(jmxUserDefineVariable.getUseName())) {
                            String value = jmxParamFileMap.get(oldName);
                            String oldName1 = oldName.replace(jmxUserDefineVariable.getUseName(), jmxUserDefineVariable.getVarValue());

                            int lastIndex1 = oldName1.lastIndexOf("/") + 1;
                            int lastIndex2 = oldName1.lastIndexOf("\\") + 1;

                            if (lastIndex1 > -1 || lastIndex2 > -1) {
                                if (lastIndex1 > lastIndex2) {
                                    String newName = oldName1.substring(lastIndex1);
                                    newMap.put(newName, value);
                                } else{
                                    String newName = oldName1.substring(lastIndex2);
                                    newMap.put(newName, value);
                                }
                            }
                            break;
                        } else {
                            //判断是不是对比到最后一个参数文件 如果是
                            if (i == jmxUserDefineVariables.size() - 1) {
                                String value = jmxParamFileMap.get(oldName);
                                int lastIndex1 = oldName.lastIndexOf("/") + 1;
                                int lastIndex2 = oldName.lastIndexOf("\\") + 1;

                                if (lastIndex1 > -1 || lastIndex2 > -1) {
                                    if (lastIndex1 > lastIndex2) {
                                        String newName = oldName.substring(lastIndex1);
                                        newMap.put(newName, value);
                                    } else{
                                        String newName = oldName.substring(lastIndex2);
                                        newMap.put(newName, value);
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }
        //未使用用户自定义变量
        else {
            if (jmxParamFileMap.size() > 0) {
                for (Map.Entry<String, String> entiry : jmxParamFileMap.entrySet()) {
                    String oldName = entiry.getKey();
                    String value = jmxParamFileMap.get(oldName);

                    int lastIndex1 = oldName.lastIndexOf("/") + 1;
                    int lastIndex2 = oldName.lastIndexOf("\\") + 1;

                    if (lastIndex1 > -1 || lastIndex2 > -1) {
                        if (lastIndex1 > lastIndex2) {
                            String newName = oldName.substring(lastIndex1);
                            newMap.put(newName, value);
                        } else{
                            String newName = oldName.substring(lastIndex2);
                            newMap.put(newName, value);
                        }
                    }
                }
            }
        }

        for (MultipartFile multipartFile : file) {
            String fileName = multipartFile.getOriginalFilename();
            List<JmxParamfile> jmxParamfiles = paramfileService.list(Wrappers.<JmxParamfile>lambdaQuery().eq(JmxParamfile::getScriptId, scriptId).eq(JmxParamfile::getFileName, fileName));
            if (jmxParamfiles.size() > 0) {
                //删除原有的参数文件，并删除记录
                for (JmxParamfile jmxParamfile : jmxParamfiles) {
                    String fullFileName = Constant.PARAM_FILE_SERVER_DIR + "/" + jmxParamfile.getId() + "/" + fileName;
                    FileUtil.del(new File(fullFileName));
                    paramfileService.removeById(jmxParamfile.getId());
                }
            }

            //保存新上传的记录
            JmxParamfile jmxParamfile = new JmxParamfile();
            jmxParamfile.setCreateBy(SessionUtil.getCurrentUser());
            jmxParamfile.setCreateTime(LocalDateTime.now());
            jmxParamfile.setFileName(fileName);
            jmxParamfile.setVariablesName(jmxParamFileMap.get(fileName));
            jmxParamfile.setScriptId(scriptId);
//            jmxParamfile.setPath();
            paramfileService.save(jmxParamfile);

            //上传新的参数文件到文件服务器
            String fullFileName = Constant.PARAM_FILE_SERVER_DIR + "/" + jmxParamfile.getId() + "/" + fileName;
            File newFile = FileUtil.touch(new File(fullFileName));
            FileUtil.writeFromStream(multipartFile.getInputStream(), newFile, true);

            jmxParamfile.setPath(fullFileName);
            paramfileService.updateById(jmxParamfile);
        }
    }

    @Override
    public List<JmxParamfile> getParamfilesByScriptId(Integer scriptId) {
        List<JmxParamfile> list = list(Wrappers.<JmxParamfile>lambdaQuery().eq(JmxParamfile::getScriptId, scriptId));
        return list;
    }

    @Override
    public IPage<JmxParamfile> bindPageList(JmxParamfileVO vo) {
        IPage<JmxParamfile> page = new Page<>(vo.getCurrentPage(), vo.getPageSize());
        Wrapper<JmxParamfile> wrapper = Wrappers.query();
        if(Double.isNaN(vo.getScriptId())) {
            wrapper = Wrappers.<JmxParamfile>lambdaQuery()
                    .eq(JmxParamfile::getScriptId, vo.getScriptId());
        }
        IPage<JmxParamfile> data = page(page, wrapper);
        return data;
    }
}
